const express = require('express');
const router = express.Router();
const Joi = require('joi');
const pool = require('../utils/db.js');
const Response = require('../utils/Response.js');
const utils = require('../utils/utils.js');

// 查询问诊会话列表
router.post('/chat/list', async (req, resp) => {
  // 从tokenPayload中拿到uid
  let uid = req.tokenPayload.uid || req.body.uid;;
  if (!uid) return resp.send(Response.error(400, "uid not playload in token or req!"));
  //执行查询任务
  // let sql = `select m.*,d.avatar d_avatar,d.name d_name,d.grade d_grade, u.name u_name, u.avatar u_avatar, u.birthday u_birthday, u.gender u_gender from inquiries_msg m 
  // join doctor d on m.did=d.uid
  // join user u on m.uid=u.uid
  // where m.uid=? or m.did=?
  // group by sid desc;`;
  let sql = `select
  m.*,
  d.avatar d_avatar,
  d.name d_name,
  d.grade d_grade,
  u.name u_name,
  u.avatar u_avatar,
  u.birthday u_birthday,
  u.gender u_gender,
  count(msg.state) unread, (
      SELECT
          CASE lm.type
              WHEN 'img' THEN '[图片]'
              WHEN 'medh' THEN '[病史]'
              ELSE lm.content
          END AS lmm
  ) lsatmsg,
  lm.sendtime updatetime
from inquiries_msg m
  left join msg on msg.sid = m.sid and msg.recipient = ? and msg.state = 0
  left join doctor d on m.did = d.uid
  left join user u on m.uid = u.uid
  join msg lm on lm.sendtime = (
      select max(cm.sendtime)
      from msg cm
      where cm.sid = m.sid
  )
where
  m.uid = ?
  or m.did = ?
group by updatetime desc`;
  try {
    let resdb = await utils.query(sql, [uid, uid, uid]);
    resp.send(Response.ok(resdb, "查询成功"));
  } catch (error) {
    resp.send(Response.error(500, error));
  }
});

// 查询会话的所有消息
router.post('/chat/details', async (req, resp) => {
  let { sid } = req.body;
  // 从tokenPayload中拿到uid
  let uid = req.tokenPayload.uid || req.body.uid;;
  if (!uid) return resp.send(Response.error(400, "uid not playload in token or req!"));
  //执行查询任务
  let sql = `select * from msg where sid=?`;
  // 更改消息的读取状态
  let read_sql = `update msg   
  set state=1 where sid=? and recipient=?`;
  try {
    await utils.query(read_sql, [sid, uid]);
    let resdb = await utils.query(sql, [sid]);
    resp.send(Response.ok(resdb, "查询成功"));
  } catch (error) {
    resp.send(Response.error(500, error));
  }
});
module.exports = router;